package router

import (
	"github.com/gin-gonic/gin"
	"go-sec-code/database"
	"go-sec-code/utils"
	"log"
	"net/http"
	"strings"
)

type CsrfHandler struct {
}

func NewCsrfHandler() *CsrfHandler {
	return &CsrfHandler{}
}

func (handler *CsrfHandler) RegisterRoutes(r *gin.RouterGroup) {
	r.GET("/reset_password", handler.ResetPassword)
}

func (handler *CsrfHandler) ResetPassword(ctx *gin.Context) {
	// 校验referer是否可信
	referer := ctx.GetHeader("Referer")
	if (!strings.HasPrefix(referer, "http://172.30.14.69/")) {
		ctx.String(http.StatusBadRequest, "Invalid referer: %v", referer)
		return
	}

	// 校验token
	csrfToken := ctx.GetHeader("x-csrf-token") // 获取客户端传入的token
	serverToken := getServerToken()	// 获取服务端token
	if csrfToken != serverToken {
		ctx.String(http.StatusBadRequest, "Invalid token: %v", csrfToken)
		return
	}


	username := ctx.Query("username")
	oldPassword := ctx.Query("oldPassword")
	newPassword := ctx.Query("newPassword")
	log.Printf("new username: %v, password: %v", username, newPassword)

	mysqlUser := database.NewMysqlUser()
	db, _ := mysqlUser.ConnectDB()

	// 校验原密码
	user := mysqlUser.SelectByName(db, username, "")[0]
	if utils.Md5(oldPassword) != user.Password {
		ctx.String(http.StatusBadRequest, "Wrong password")
		return
	}
	// 执行重置密码的操作
	mysqlUser.UpdatePassword(db, username, newPassword)

	ctx.String(http.StatusOK, "Reset succ")
}

func getServerToken() string {
	// FIXME 伪代码，真实环境应该从session或redis缓存等中取
	return "f872e082-c81e-4fb5-a813-6dcec1ec3317"
}
